package com.joysuch.wwyt.api.dataaccess;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.api.dataaccess.bean.*;
import com.joysuch.wwyt.api.entity.ApiAlarmSubscribe;
import com.joysuch.wwyt.api.service.ApiAlarmSubscribeService;
import com.joysuch.wwyt.bp.entity.AlarmMessage;
import com.joysuch.wwyt.bp.entity.bean.AlarmMeaasgeSearchBean;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.entity.inspect.BPInspectPoint;
import com.joysuch.wwyt.bp.enums.ApiAlarmSubTypeEnum;
import com.joysuch.wwyt.bp.enums.ApiAlarmTypeEnum;
import com.joysuch.wwyt.bp.repository.BPInspectPointRepository;
import com.joysuch.wwyt.bp.repository.BpContractorDao;
import com.joysuch.wwyt.bp.service.AlarmMessageService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.MapUtils;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.entity.BaseImageRepository;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.repository.BaseImageRespositoryDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.repository.MhAlarmMessageDao;
import com.joysuch.wwyt.mh.websocket.MonitorPointDataWebSocket;
import com.joysuch.wwyt.mh.websocket.WebsocketDataType;
import com.joysuch.wwyt.monitoringcenter.bean.LocateAlarmBean;
import com.joysuch.wwyt.monitoringcenter.bean.LocateLoginRespDto;
import com.joysuch.wwyt.monitoringcenter.service.AlarmCenterService;
import com.joysuch.wwyt.monitoringcenter.service.LocateServerService;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.entity.dsl.QRiskEvaluationAlarmMesage;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.risk.repository.RiskEvaluationAlarmMesageDao;
import com.joysuch.wwyt.util.INetUtil;
import com.joysuch.wwyt.util.IpUtil;
import com.joysuch.wwyt.workflow.api.service.NewProcessService;
import com.joysuch.wwyt.workflow.bean.ProcessMapListBean;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrientationDataSyncServiceImpl implements OrientationDataSyncService {

    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private LocateServerService locateServerService;
    @Autowired
    private BaseConfigService baseConfigService;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BPInspectPointRepository inspectPointDao;
    @Autowired
    private MhAlarmMessageDao mhAlarmMessageDao;
    @Autowired
    private RiskEvaluationAlarmMesageDao riskEvaluationAlarmMesageDao;
    @Autowired
    private AlarmCenterService alarmCenterService;
    @Autowired
    private AlarmMessageService alarmMessageService;
    @Autowired
    private BaseImageRespositoryDao baseImageRespositoryDao;
    @Autowired
    private BpContractorDao bpContractorDao;
    @Autowired
    private ApiAlarmSubscribeService apiAlarmSubscribeService;

    @Autowired
    private NewProcessService newProcessService;


    //<tenentId + ":" + orgCode,verson>
    private static Map<String, Integer> versionMap = new ConcurrentHashMap<>();

    /**
     * 风险区域同步至人员定位
     *
     * @param all  风险区域
     * @param flag 同步的方法类型 add alter delete
     */
    @Override
    public void riskDistrict(List<RiskDistrict> all, String flag) {
        log.info("风险区域同步,当前风险区域数量{}" + all.size() + ",同步的方法类型{}" + flag);
        if (CollectionUtils.isEmpty(all) || flag == null || (!flag.equals("addArea") && !flag.equals("alterArea") && !flag.equals("deleteArea"))) {
            return;
        }
        if (!baseConfigService.checkIfSync()) {
            return;
        }
        //组装数据
        if (flag.equals("addArea") || flag.equals("alterArea")) {
            for (RiskDistrict district : all) {
                saveDistrict(district, flag);
            }
        } else if (flag.equals("deleteArea")) {
            OrientationRiskDistrictDeleteBean bean = getDistrictDeleteBean(all);
            String errorMessage = "";
            try {
                ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, flag);
                LocateLoginRespDto dto = responseEntity.getBody();
                if (responseEntity.getStatusCode() == null || responseEntity.getStatusCode() != HttpStatus.OK) {
                    errorMessage = dto.getErrMsg();
                    log.error("风险区域同步--删除区域 接口错误,data:{},errMsg:{}", bean, dto.getErrMsg());
                } else {
                    if (StringUtils.isNotBlank(dto.getErrMsg())) {
                        if (dto.getErrMsg().contains("从开放平台获取joysuchclient失败向开放平台删除区域失败")) {
                            errorMessage = "开放平台删除区域失败";
                        } else {
                            errorMessage = dto.getErrMsg();
                        }
                    }
                }
            } catch (Exception e) {
                log.error("风险区域同步---删除区域 同步失败errMsg:{}", e, e.getMessage());
            }
            if (StringUtils.isNotBlank(errorMessage)) {
                throw new IllegalArgumentException(errorMessage);
            }
        }
    }

    //新增区域
    private void addArea(OrientationRiskDistrictSaveBean bean, Class clazz, String flag, RiskDistrict district) {
        try {
            ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, flag);
            LocateLoginRespDto dto = responseEntity.getBody();
            if (responseEntity != null && responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                String uniqueId = String.valueOf(dto.getData());
                if (uniqueId != null) {
                    //将雪花id保存在本地
                    saveUniqueId(district, uniqueId);
                } else {
                    log.error("风险区域同步---增加区域 返回的uniqueId为空,data:{},errMsg:{}", bean, dto.getErrMsg());
                }
            }
        } catch (Exception e) {
            log.error("风险区域同步---增加区域 同步失败,data:{},errMsg:{}", bean, e.getMessage());
        }
    }

    //修改区域
    private void alterArea(OrientationRiskDistrictSaveBean bean, Class clazz, String flag) {
        try {
            ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, flag);
            LocateLoginRespDto dto = responseEntity.getBody();
            if (responseEntity.getStatusCode() == null || responseEntity.getStatusCode() != HttpStatus.OK) {
                log.error("风险区域同步---修改区域 返回的uniqueId为空,data:{},errMsg:{}", bean, dto.getErrMsg());
            }
        } catch (Exception e) {
            log.error("风险区域同步---修改区域 同步失败,data:{},errMsg:{}", bean, e.getMessage());
        }
    }

    /**
     * 获取报警模板列表
     *
     * @param bean
     * @return
     */
    @Override
    public ResultBean alarmTemplate(OrientationSearchBean bean) {
        if (bean.getPage() == null || bean.getSize() == null) {
            return ResultBean.pageData(new ArrayList<>(), 0);
        }
        bean.setBuildId(locateServerService.getBuildId());
        bean.setType(1);
        try {
            if (this.getAlarmSwitch()) {
                ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, "pageAlarmTemplate");
                LocateLoginRespDto dto = responseEntity.getBody();
                if (responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                    List<OrientationAlarmTemplateReturnItemBean> record = (List<OrientationAlarmTemplateReturnItemBean>) dto.getData();
                    if (CollectionUtils.isEmpty(record)) {
                        return ResultBean.pageData(new ArrayList<>(), dto.getLength());
                    } else {
                        return ResultBean.pageData(record, dto.getLength());
                    }
                } else {
                    log.error("获取报警模板列表接口错误,data:{},errMsg:{}", bean, dto.getErrMsg());
                }
            }
        } catch (Exception e) {
            log.error("获取报警模板列表失败,data:{},errMsg:{}", bean, e.getMessage());
        }
        return ResultBean.pageData(new ArrayList<>(), 0);
    }


    @Override
    public void renewLocateAlarmData(Long tenentId, String orgCode, String flag) {
        if (flag.equals("pageCertificateAlarm")) {
            //作业报警列表
            List<OrientationPageAlarmCertificateOrAreaBean> certificateAlarmList = pageCertificateOrAreaAlarm(tenentId, orgCode, new OrientationSearchBean(0, 100, "pageCertificateAlarm"));
            MonitorPointDataWebSocket.sendInfo(certificateAlarmList, WebsocketDataType.LOCATE_CERTIFICATE_ALARM.getIndex());
        } else if (flag.equals("pageAreaAlarm")) {
            //区域人员报警列表
            List<OrientationPageAlarmCertificateOrAreaBean> areaAlarmList = pageCertificateOrAreaAlarm(tenentId, orgCode, new OrientationSearchBean(0, 100, "pageAreaAlarm"));
            MonitorPointDataWebSocket.sendInfo(areaAlarmList, WebsocketDataType.LOCATE_AREA_ALRAM.getIndex());
        } else if (flag.equals("pagCarAlarm")) {
            //车辆报警
            List<OrientationPageAlarmCertificateOrAreaBean> certBeans = pageCertificateOrAreaAlarm(tenentId, orgCode, new OrientationSearchBean(0, 100, "pagCarAlarm"));
            MonitorPointDataWebSocket.sendInfo(Lists.newArrayList(certBeans), WebsocketDataType.LOCATE_CAR_ALARM.getIndex());
        }
    }

    @Override
    public void renewAlarmCount(Long tenentId, String orgCode) {
        //数量
        OrientationAlarmCountBean alarmCountBean = alarmMessageCount(tenentId, orgCode);
        if (alarmCountBean != null) {
            MonitorPointDataWebSocket.sendInfo(Lists.newArrayList(alarmCountBean), WebsocketDataType.LOCATE_ALRAM_COUNT.getIndex());
        }
    }


    @Override
    public OrientationAlarmCountBean alarmMessageCount(Long tenentId, String orgCode) {
        OrientationAlarmCountBean bean = new OrientationAlarmCountBean();
        //本地 危险源报警+区域报警+巡检排查+AI报警
        bean = getWwytAlarmCount(tenentId, orgCode);
        //定位报警总数,区分3.x和4.x
        BaseConfig config = baseConfigService.findConfig(tenentId, orgCode, "locate.version");
        if (config != null && config.getValue().equals("4.x")) {
            Map<String, Integer> alarmMap = getAlarmTypesNumber(tenentId, orgCode);
            if (!CollectionUtils.isEmpty(alarmMap)) {
                bean.setJobAlarmNum(alarmMap.get("jobAlarmNum"));
                bean.setAreaAlarmNum(alarmMap.get("areaAlarmNum"));
                bean.setVehAlarmNum(alarmMap.get("VehAlarmNum"));
                bean.setAllCount(bean.getAllCount() + bean.getJobAlarmNum() + bean.getAreaAlarmNum() + bean.getVehAlarmNum());
            }
        } else {
            LocateAlarmBean bean1 = createBean(tenentId, orgCode);
            ResultBean locateAlarmResult = locateServerService.getLocateAlarm(bean1);
            if (null != locateAlarmResult) {
                Long areaAlarmNum = locateAlarmResult.getLength();
                bean.setAreaAlarmNum(null == areaAlarmNum ? 0 : areaAlarmNum.intValue());
                bean.setAllCount(bean.getAllCount() + bean.getAreaAlarmNum());
            }
        }
        bean.setTenentId(tenentId);
        bean.setOrgCode(orgCode);
        return bean;
    }

    /**
     * 创建搜索bean
     *
     * @return
     */
    private LocateAlarmBean createBean(Long tenentId, String orgCode) {
        String buildId = locateServerService.getBuildIdByTenentIdAndOrgCode(tenentId, orgCode);
        LocateAlarmBean bean = new LocateAlarmBean();
        bean.setBuildId(buildId);
        bean.setFlag(false);
        bean.setAlarmState(1);
        bean.setPageNumber(1);
        bean.setPageSize(15);
        return bean;

    }


//    private Integer getLocateAlarmCount(Long tenentId, String orgCode) {
//        BaseConfig config = baseConfigService.findConfig(tenentId, orgCode, BaseConfigCodes.LOCATE_VERSION);
//        if (config != null && config.getValue().equals("4.x")) {
//            Integer alength = getAlarmNumber(tenentId, orgCode);
//            if (alength != null) {
//                return alength;
//            }
//        } else {
//            //兼容旧版本
//            BaseConfig buildConfig = baseConfigService.findConfig(tenentId, orgCode, BaseConfigCodes.LOCATE_CURRENT_BUILD_ID);
//            if (buildConfig != null) {
//                return locateServerService.getLocateAlarmCount(buildConfig.getValue());
//            }
//        }
//        return null;
//    }

    private OrientationAlarmCountBean getWwytAlarmCount(Long tenentId, String orgCode) {
        int count = mhAlarmMessageDao.countByStates(tenentId, orgCode);
        QRiskEvaluationAlarmMesage qm = QRiskEvaluationAlarmMesage.riskEvaluationAlarmMesage;
        Predicate p = qm.state.eq(0);
        int count1 = riskEvaluationAlarmMesageDao.countByState(tenentId, orgCode);
        Integer count2 = alarmCenterService.inspectCount(tenentId, orgCode);
        Integer count3 = alarmMessageService.aiAlarmMessageCount(tenentId, orgCode, Lists.newArrayList(ApiAlarmTypeEnum.AI.getId()));
        OrientationAlarmCountBean bean = new OrientationAlarmCountBean();
        bean.setAllCount(count + count1 + count2 + count3);
        bean.setMajorHazardCount(count);
        bean.setRiskAreaCount(count1);
        bean.setInspectCount(count2);
        bean.setAiAlarmCount(count3);
        return bean;
    }

    @Override
    public ResultBean getPageCertificateOrAreaAlarm(Long tenantId, String orgCode, OrientationSearchBean bean) {
        List<OrientationPageAlarmCertificateOrAreaBean> dataList = pageCertificateOrAreaAlarm(tenantId, orgCode, bean);
        BaseConfig config = baseConfigService.findConfig(tenantId, orgCode, "locate.version");
        int totalCount = 0;
        if (config != null && config.getValue().equals("4.x")) {
            Map<String, Integer> alarmMap = getAlarmTypesNumber(tenantId, orgCode);
            if (!CollectionUtils.isEmpty(alarmMap)) {
                if (bean.getFlag().equals("pageCertificateAlarm")) {
                    totalCount = alarmMap.get("jobAlarmNum").intValue();
                } else if (bean.getFlag().equals("pageAreaAlarm")) {
                    totalCount = alarmMap.get("areaAlarmNum").intValue();
                }
            }
        } else {
            LocateAlarmBean bean1 = createBean(tenantId, orgCode);
            ResultBean locateAlarmResult = locateServerService.getLocateAlarm(bean1);
            if (null != locateAlarmResult) {
                Long areaAlarmNum = locateAlarmResult.getLength();
                totalCount = areaAlarmNum == null ? 0 : areaAlarmNum.intValue();
            }
        }
        return ResultBean.pageData(dataList, totalCount);
    }


    /**
     * 获取作业/区域报警
     *
     * @param tenentId
     * @param orgCode
     * @param bean
     * @return
     */
    @Override
    public List<OrientationPageAlarmCertificateOrAreaBean> pageCertificateOrAreaAlarm(Long tenentId, String orgCode, OrientationSearchBean bean) {
        List<OrientationPageAlarmCertificateOrAreaBean> records = new ArrayList<>();
        AlarmMeaasgeSearchBean searchBean = new AlarmMeaasgeSearchBean();
        searchBean.setTenentId(tenentId);
        searchBean.setOrgCode(orgCode);
        if (bean.getFlag().equals("pageCertificateAlarm")) {
            searchBean.setAlarmType(ApiAlarmTypeEnum.JOBA_LARM_EVENT.getId());
        } else if (bean.getFlag().equals("pageAreaAlarm")) {
            searchBean.setAlarmType(ApiAlarmTypeEnum.AREA_ALARM.getId());
        } else if (bean.getFlag().equals("pagCarAlarm")) {
            searchBean.setAlarmType(ApiAlarmTypeEnum.ALARM_EVENT.getId());
        }
        searchBean.setPage(bean.getPage());
        searchBean.setSize(bean.getSize());
        //大屏只展示未处理的
        searchBean.setStatus(0);
        Page<AlarmMessage> pageData = alarmMessageService.getAlarmMessagePageData(searchBean);
        for (AlarmMessage message : pageData.getRecords()) {
            OrientationPageAlarmCertificateOrAreaBean dataBean = new OrientationPageAlarmCertificateOrAreaBean();
            dataBean.setId(message.getId());
            dataBean.setTenentId(tenentId);
            dataBean.setOrgCode(orgCode);
            dataBean.setModule(ApiAlarmTypeEnum.getNameById(message.getAlarmType()));
            dataBean.setMoudle(bean.getFlag());
            dataBean.setSerialNumber(message.getSerialNumber());
            dataBean.setProcessInstanceId(message.getProcessInstanceId());
            String sn = "snIsNull";
            if (StringUtils.isNotBlank(message.getSn())) {
                sn = message.getSn();
            }
            dataBean.setSn(sn);
            dataBean.setAlarmInfo(message.getAlarmInfo());
            if (message.getAlarmTime() != null) {
                dataBean.setAlarmTime(DateUtil.format(message.getAlarmTime(), DatePattern.NORM_DATETIME_PATTERN));
            }
            String areaName = null;
            if (StringUtils.isNotBlank(message.getRails())) {
                List<OrientationV3RailBean> rails = JSONUtil.toList(message.getRails(), OrientationV3RailBean.class);
                if (!CollectionUtils.isEmpty(rails)){
                    areaName = rails.get(0).getRailName();
                    dataBean.setRails(rails);
                }
            }
            dataBean.setAreaName(areaName);
            dataBean.setAlarmTypeName(message.getSubTypeName());
            dataBean.setStatus(message.getStatus().intValue() == 1 ? 0 : 1);
            records.add(dataBean);
        }
        return records;
    }

    /**
     * 批量处理作业/区域报警
     *
     * @param bean
     * @return
     */
    @Override
    public ResultBean pageSolveAlarm(OrientationSearchBean bean) {
        bean.setBuildId(locateServerService.getBuildId());
        try {
            if (this.getAlarmSwitch()) {
                ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, bean.getFlag());
                LocateLoginRespDto dto = responseEntity.getBody();
                if (responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                    //刷新报警数据
                    //renewLocateAlarmData(Context.getCurrentTenantId(), Context.getCompanyCode().substring(0, 7), bean.getFlag());
                    return ResultBean.success("");
                } else {
                    log.error("定位报警处理接口错误,data:{},errMsg:{}", bean, dto.getErrMsg());
                }
            }
        } catch (Exception e) {
            log.error("定位报警处理失败,data:{},errMsg:{}", bean, e.getMessage());
        }
        return ResultBean.defaultSuccessResult();
    }

    /**
     * 承包商同步至人员定位
     *
     * @param all
     * @param flag
     */
    @Override
    public void contractor(List<BpContractor> all, String flag) {
        log.info("承包商同步,当前承包商数量{}" + all.size() + ",同步的方法类型{}" + flag);
        if (CollectionUtils.isEmpty(all) || flag == null || (!flag.equals("saveContractor") && !flag.equals("deleteContractor"))) {
            return;
        }

        if (flag.equals("saveContractor")) {
            for (BpContractor contractor : all) {
                OrientationContractorBean bean = getContractorSaveBean(contractor);
                try {
                    ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, flag);
                    if (responseEntity != null && responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                        log.info("承包商同步---保存 数据同步成功,data:{}", bean);
                        contractor.setLocateSync(true);
                        bpContractorDao.save(contractor);
                    } else {
                        if (responseEntity == null) {
                            log.error("承包商同步---保存 数据同步错误...ResponseEntity is null");
                            contractor.setLocateSync(false);
                            bpContractorDao.save(contractor);
                        } else {
                            LocateLoginRespDto dto = responseEntity.getBody();
                            if (responseEntity.getStatusCode() == null && responseEntity.getStatusCode() != HttpStatus.OK) {
                                log.error("承包商同步--保存 接口错误,data:{},errMsg:{}", bean, dto.getErrMsg());
                                contractor.setLocateSync(false);
                                bpContractorDao.save(contractor);
                            }
                            if (StringUtils.isNotBlank(dto.getErrMsg())) {
                                log.error("承包商同步--保存 接口错误,data:{},errMsg:{}", bean, dto.getErrMsg());
                                contractor.setLocateSync(false);
                                bpContractorDao.save(contractor);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("承包商同步--保存 ,data:{},errMsg:{}", bean, e.getMessage());
                    contractor.setLocateSync(false);
                    bpContractorDao.save(contractor);
                }
            }
        } else if (flag.equals("deleteContractor")) {
            OrientationContractorBean bean = getContractorDeleteBean(all);
            try {
                ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, flag);
                if (responseEntity == null) {
                    log.error("承包商同步---删除 数据同步错误...ResponseEntity is null");
                } else {
                    LocateLoginRespDto dto = responseEntity.getBody();
                    if (responseEntity.getStatusCode() == null && responseEntity.getStatusCode() != HttpStatus.OK) {
                        log.error("承包商同步--删除 接口错误,data:{},errMsg:{}", bean, dto.getErrMsg());
                    }
                }
            } catch (Exception e) {
                log.error("承包商同步--删除 ,errMsg:{}", e);
            }
        }
    }

    /**
     * sn号是否在区域
     *
     * @return
     */
    @Override
    public ResultBean checkSnInArea(Long userId, Long pointId) {
        OrientationCheckSnInAreaReturnBoxBean returnBoxBean = new OrientationCheckSnInAreaReturnBoxBean();
        String mesage = "";
        OrientationCheckSnInAreaBoxBean bean = getSnInAreaBean(userId, pointId, mesage);
        returnBoxBean.setMessage(bean.getMessage());
        try {
            log.info("SN号同步数据{}" + bean.getBean());
            ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean.getBean(), LocateLoginRespDto.class, "checkSnInArea");
            if (responseEntity == null) {
                log.error("sn号是否在区域同步 数据同步错误...ResponseEntity is null");
            } else {
                LocateLoginRespDto dto = responseEntity.getBody();
                if (StringUtils.isNotBlank(dto.getErrMsg())) {
                    if (StringUtils.isBlank(bean.getMessage())) {
                        mesage = "人员暂时无法定位,请重试或者直接开始";
                        returnBoxBean.setMessage(mesage);
                    }
                }
                if (responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                    List<LinkedHashMap> rt = (List<LinkedHashMap>) dto.getData();
                    Boolean inRail = (Boolean) rt.get(0).get("inRail");
                    Long time = (Long) ((LinkedHashMap) rt.get(0).get("location")).get("time");
                    //true 0 false 1  其他 2
                    if (inRail) {
                        //时间超过1分钟 报错
                        if (time != null && time + 2 * 60 * 1000 < System.currentTimeMillis()) {
                            returnBoxBean.setFlag(2);
                            returnBoxBean.setMessage("人员位置在区域内,但位置实时时间正确，请重试或者直接开始");
                        } else {
                            returnBoxBean.setFlag(0);
                        }
                        return ResultBean.success(returnBoxBean);
                    } else {
                        returnBoxBean.setFlag(1);
                        return ResultBean.success(returnBoxBean);
                    }
                } else {
                    log.error("sn号是否在区域同步 接口错误,data:{},errMsg:{}", bean, dto.getErrMsg());
                }
            }
        } catch (Exception e) {
            log.error("sn号是否在区域同步 ,data:{}" + bean, e);
        }
        if (StringUtils.isBlank(bean.getMessage())) {
            returnBoxBean.setMessage("系统繁忙,请稍后重试...");
        }
        returnBoxBean.setFlag(2);
        return ResultBean.success(returnBoxBean);
    }

    /**
     * 获取报警总数
     *
     * @return
     */
    @Override
    public Integer getAlarmNumber(Long tenentId, String orgCode) {
//        OrientationSearchBean bean = new OrientationSearchBean();
//        bean.setBuildId(locateServerService.getBuildIdByTenentIdAndOrgCode(tenentId, orgCode));
//        try {
//            if (this.getAlarmSwitch(tenentId, orgCode)) {
//                ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, "getAlarmNumber", tenentId, orgCode);
//                if (responseEntity == null) {
//                    log.error("获取报警总数 数据同步错误...ResponseEntity is null");
//                } else {
//                    LocateLoginRespDto dto = responseEntity.getBody();
//                    if (null != dto) {
//                        if (responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
//                            Integer record = (Integer) dto.getData();
//                            return record;
//                        } else {
//                            log.error("获取报警总数接口错误,data:{},errMsg:{}", bean, dto.getErrMsg());
//                        }
//                    }
//                }
//            }
//        } catch (Exception e) {
//            log.error("获取报警总数 数据同步错误{}", e);
//        }
        return null;
    }

    /**
     * 获取各报警类型数量
     *
     * @return
     */
    @Override
    public Map<String, Integer> getAlarmTypesNumber(Long tenentId, String orgCode) {
        List<AlarmMessage> list = alarmMessageService.getAlarmTypesNumber(tenentId, orgCode);
        Map<String, Integer> map = new HashMap<>();
        map.put("areaAlarmNum", 0);
        map.put("VehAlarmNum", 0);
        map.put("jobAlarmNum", 0);
        list.forEach(m -> {
            Integer num = null;
            String str = "";
            if (m.getAlarmTypeName().equals("areaAlarm")) {
                str = "areaAlarmNum";
                num = map.get("areaAlarmNum");
            } else if (m.getAlarmTypeName().equals("alarmEvent")) {
                str = "VehAlarmNum";
                num = map.get("VehAlarmNum");
            } else if (m.getAlarmTypeName().equals("jobAlarmEvent")) {
                str = "jobAlarmNum";
                num = map.get("jobAlarmNum");
            }
            map.put(str, num + 1);
        });
        return map;
    }

    @Override
    public String getV2Token() {
        if (baseConfigService.checkIfSync()) {
            return locateServerService.getLoginToken();
        } else {
            return null;
        }
    }


    @Override
    public String getV3ScreenToken() {
        if (baseConfigService.checkIfSync()) {
            return locateServerService.getV3ScreenToken();
        } else {
            return null;
        }
    }


    @Override
    public Integer getV3BindersVersion(OrientationSearchBean bean, Long tenentId, String orgCode) {
        Integer version = null;
        if (getAlarmSwitch(tenentId, orgCode)) {
            ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, "getV3BindersVersion", tenentId, orgCode);
            if (responseEntity == null) {
                log.error("获取大屏人员版本错误...ResponseEntity is null");
            } else {
                LocateLoginRespDto dto = responseEntity.getBody();
                if (null != dto) {
                    if (responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                        version = (Integer) dto.getData();
                    } else {
                        log.error("获取大屏人员版本接口错误,errMsg:{}", dto.getErrMsg());
                    }
                }
            }
        }
        return version;
    }


    @Override
    public OrientationScreenBindersBean getV3ScreenBinders(OrientationSearchBean bean, Long tenentId, String orgCode) {
        if (baseConfigService.checkIfSync(tenentId, orgCode)) {
            ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, "getV3ScreenBinders", tenentId, orgCode);
            if (responseEntity == null) {
                log.error("获取大屏人员错误...ResponseEntity is null");
            } else {
                LocateLoginRespDto dto = responseEntity.getBody();
                if (null != dto) {
                    if (responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                        if (null != dto && dto.getData() != null) {
                            String string = JSONObject.toJSONString(dto.getData());
                            OrientationScreenBindersBean bindersBean = JSONObject.parseObject(string, OrientationScreenBindersBean.class);
                            LinkedHashMap<String, OrientationScreenBinderBean> data = bindersBean.getData();
                            if (!CollectionUtils.isEmpty(data)) {
                                //获取帽子map
                                Map<String, Long> imageMap = this.getImageMap(data);
                                for (Map.Entry<String, OrientationScreenBinderBean> entry : data.entrySet()) {
                                    OrientationScreenBinderBean value = entry.getValue();
                                    if (value != null && StringUtils.isNotBlank(value.getIconUniqueId()) && imageMap.get(value.getIconUniqueId()) != null) {
                                        value.setImageId(imageMap.get(value.getIconUniqueId()));
                                    }
                                }
                            }
                            return bindersBean;
                        }
                    } else {
                        log.error("获取大屏人员错误,errMsg:{}", dto.getErrMsg());
                    }
                }
            }
        }
        return null;
    }

    private Map<String, Long> getImageMap(LinkedHashMap<String, OrientationScreenBinderBean> data) {
        Map<String, Long> imageMap = new HashMap<>();
        if (CollectionUtils.isEmpty(data)) {
            return imageMap;
        }
        List<String> iconUniqueIds = data.values().stream().filter(d -> d != null && StringUtils.isNotBlank(d.getIconUniqueId()))
                .map(OrientationScreenBinderBean::getIconUniqueId).distinct().collect(Collectors.toList());
        List<BaseImageRepository> images = baseImageRespositoryDao.findByUniqueIds(iconUniqueIds);
        if (CollectionUtils.isEmpty(images)) {
            return imageMap;
        }
        imageMap = images.stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i.getId()));
        return imageMap;
    }

    @Override
    public List<OrientationScreenBinderBean> getScreenBinderData(Long tenentId, String orgCode, String source) {
        List<OrientationScreenBinderBean> list = new ArrayList<>();
        String buildId = locateServerService.getBuildIdByTenentIdAndOrgCode(tenentId, orgCode);
        OrientationSearchBean bean = new OrientationSearchBean(buildId);
        //获取人员版本号
        Integer version = getV3BindersVersion(bean, tenentId, orgCode);
        if (version == null) {
            return list;
        }
        //webSocket启动 每次都推送
        //版本号相同 则不推送数据
        if (StringUtils.isNotBlank(source) && source.equals("webSocket")) {
            list = covertBinderData(tenentId, orgCode, version, bean);
        } else {
            if (CollectionUtils.isEmpty(versionMap)) {
                list = covertBinderData(tenentId, orgCode, version, bean);
            } else {
                if (!version.equals(versionMap.get(getVersionKey(tenentId, orgCode)))) {
                    list = covertBinderData(tenentId, orgCode, version, bean);
                }
            }
        }
        return list;
    }

    private String getVersionKey(Long tenentId, String orgCode) {
        return tenentId + ":" + orgCode;
    }

    @Override
    public List<OrientationScreenAreaPersonBean> getV3ScreenAreaPerson(Long tenentId, String orgCode) {
        List<OrientationScreenAreaPersonBean> beanList = new ArrayList<>();
        BaseConfig config = baseConfigService.findConfig(tenentId, orgCode, "locate.version");
        if (config != null && config.getValue().equals("3.x")) {
            return beanList;
        }
        if (getAlarmSwitch(tenentId, orgCode)) {
            String buildId = locateServerService.getBuildIdByTenentIdAndOrgCode(tenentId, orgCode);
            OrientationSearchBean bean = new OrientationSearchBean(buildId);
            ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, "getV3ScreenAreaPerson", tenentId, orgCode);
            if (responseEntity == null) {
                log.error("获取大屏人员的区域列表错误...ResponseEntity is null");
            } else {
                LocateLoginRespDto dto = responseEntity.getBody();
                if (null != dto) {
                    if (responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                        if (dto.getData() != null) {
                            String string = JSONObject.toJSONString(dto.getData());
                            beanList = JSONObject.parseArray(string, OrientationScreenAreaPersonBean.class);
                            for (OrientationScreenAreaPersonBean b : beanList) {
                                b.setOrgCode(orgCode);
                                b.setTenentId(tenentId);
                            }
                        }
                    } else {
                        log.error("获取大屏人员的区域列表错误errMsg:{}", dto.getErrMsg());
                    }
                }
            }
        }
        return beanList;
    }


    @Override
    public Object getV3ScreenRegionalPopulation(Long areaId) {
        if (baseConfigService.checkIfSync()) {
            String buildId = locateServerService.getBuildId();
            OriginalRegionalPopulationBean bean = new OriginalRegionalPopulationBean(areaId, buildId);
            ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(bean, LocateLoginRespDto.class, "getV3ScreenRegionalPopulation");
            if (responseEntity == null) {
                log.error("获取大屏人车列表错误...ResponseEntity is null");
            } else {
                LocateLoginRespDto dto = responseEntity.getBody();
                if (responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                    if (dto.getData() != null) {
                        return dto.getData();
                    }
                } else {
                    log.error("获取大屏人车列表错误errMsg:{}", dto.getErrMsg());
                }
            }
        }
        return null;
    }

    private List<OrientationScreenBinderBean> covertBinderData(Long tenentId, String orgCode, Integer version, OrientationSearchBean bean) {
        List<OrientationScreenBinderBean> beanList = new ArrayList<>();
        //获取人员列表
        OrientationScreenBindersBean bindersBean = getV3ScreenBinders(bean, tenentId, orgCode);
        if (bindersBean != null && !CollectionUtils.isEmpty(bindersBean.getData())) {
            versionMap.put(getVersionKey(tenentId, orgCode), version);
            for (Map.Entry<String, OrientationScreenBinderBean> entry : bindersBean.getData().entrySet()) {
                OrientationScreenBinderBean value = entry.getValue();
                value.setTenentId(tenentId);
                value.setOrgCode(orgCode);
                beanList.add(value);
            }
        }
        return beanList;
    }

    /**
     * 获取报警同步开关
     *
     * @return
     */
    private Boolean getAlarmSwitch() {
        BaseConfig config = baseConfigService.findConfig(Context.getCurrentTenantId(), Context.getCompanyCode(), BaseConfigCodes.LOCATE_SERVICE_ALARM_OPEN);
        if (config == null || StringUtils.isBlank(config.getValue()) || config.getValue().trim().equals("true")) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean getAlarmSwitch(Long tenentId, String orgCode) {
        BaseConfig config = baseConfigService.findConfig(tenentId, orgCode, BaseConfigCodes.LOCATE_SERVICE_ALARM_OPEN);
        if (config == null || StringUtils.isBlank(config.getValue()) || config.getValue().trim().equals("true")) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchApiV3Subscribe() {
        log.info("报警订阅batchApiV3Subscribe-----------------------------START");
        try {
            //查询所有未订阅数据
            List<ApiAlarmSubscribe> datas = apiAlarmSubscribeService.findUnsubscribedDatas();
            log.info("报警订阅batchApiV3Subscribe待订阅接口数量-----------------------------dataSize{}", datas.size());
            if (cn.zlg.common.util.CollectionUtils.isEmpty(datas)) {
                log.info("报警订阅batchApiV3Subscribe-----------------------------END");
                return;
            }
            //按照orgCode tenentId将数据分组
            Map<String, List<ApiAlarmSubscribe>> dataMap = datas.stream().collect(Collectors.groupingBy(e -> {
                return e.getOrgCode() + "_" + e.getTenentId();
            }));
            List<ApiAlarmSubscribe> apiAlarmSubscribeList = new ArrayList<>();
            for (Map.Entry<String, List<ApiAlarmSubscribe>> data : dataMap.entrySet()) {
                List<ApiAlarmSubscribe> alDatas = data.getValue();
                String orgCode = alDatas.get(0).getOrgCode();
                Long tenentId = alDatas.get(0).getTenentId();
                String buildId = locateServerService.getBuildIdByTenentIdAndOrgCode(tenentId, orgCode);
                BaseConfig portConfig = baseConfigService.findConfig(tenentId, orgCode, BaseConfigCodes.WWYT_ALARM_PORT);
                alDatas.forEach(alarmSubscribe -> {
                    //订阅
                    boolean flag = apiV3Subscribe(orgCode, tenentId, buildId, alarmSubscribe.getAlarmType(), alarmSubscribe.getUrl(), portConfig);
                    if (flag) {
                        alarmSubscribe.setStatus(1);
                    }
                    apiAlarmSubscribeList.add(alarmSubscribe);
                });
            }
            apiAlarmSubscribeService.saveOrUpdateBatch(apiAlarmSubscribeList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info("报警订阅batchApiV3Subscribe-----------------------------END");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean apiV3Subscribe(String orgCode, Long tenentId, String buildId, String alarmType, String url, BaseConfig portConfig) {
        OrientationSubscribeBean suBean = convertSubscribeBean(buildId, alarmType, url, portConfig);
        return v3AlarmSubscribe(orgCode, tenentId, suBean);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean getV3Subscribe(String type, String url) {
        BaseConfig portConfig = baseConfigService.findConfig(Context.getCurrentTenantId(), Context.getCompanyCode(), BaseConfigCodes.WWYT_ALARM_PORT);
        OrientationSubscribeBean suBean = convertSubscribeBean(locateServerService.getBuildId(), type, url, portConfig);
        boolean flag = v3AlarmSubscribe(Context.getCompanyCode(), Context.getCurrentTenantId(), suBean);
        if (flag) {
            ApiAlarmSubscribe apiData = apiAlarmSubscribeService.findByAlarmTypeAndUrl(suBean.getType(), suBean.getRequestServerUrl(), Context.getCompanyCode(), Context.getCurrentTenantId());
            if (apiData != null) {
                apiData.setStatus(1);
                apiAlarmSubscribeService.saveOrUpdate(apiData);
            }
        }
        return flag;
    }

    private OrientationSubscribeBean convertSubscribeBean(String buildId, String alarmType, String url, BaseConfig portConfig) {
        OrientationSubscribeBean suBean = new OrientationSubscribeBean();
        suBean.setBuildId(buildId);
        suBean.setType(alarmType);
        String port = "8888";
        if (portConfig != null && StringUtils.isNotBlank(portConfig.getValue())) {
            port = portConfig.getValue();
        }
        String requestServerUrl = "http://" + INetUtil.getHostIp() + ":" + port + url;
        suBean.setRequestServerUrl(requestServerUrl);
        return suBean;
    }

    private boolean v3AlarmSubscribe(String orgCode, Long tenentId, OrientationSubscribeBean suBean) {
        log.info("报警订阅url--------->" + suBean.getType() + "[" + suBean.getRequestServerUrl() + "]");
        ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(suBean, LocateLoginRespDto.class, "v3Subscribe", tenentId, orgCode);
        if (responseEntity == null) {
            log.error("报警订阅错误...ResponseEntity is null");
        } else {
            LocateLoginRespDto dto = responseEntity.getBody();
            log.info("报警订阅返回信息--------->" + JSONUtil.toJsonPrettyStr(dto));
            return dto != null && StringUtils.isNotBlank(dto.getStatus()) && dto.getStatus().equals("success");
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized void getV3Alarm(OrientationV3AlarmReqBean reqBean) {
        if (reqBean.getData() == null) {
            return;
        }
        log.info("=========v3定位系统推送报警数据==========="+JSON.toJSONString(reqBean));

        OrientationV3AlarmBean alarmBean = JSONUtil.toBean(JSONUtil.toJsonPrettyStr(reqBean.getData()), OrientationV3AlarmBean.class);
        log.info("v3定位系统推送报警数据 ---------> 报警类型 = " + reqBean.getType() + " 定位数据id =" + alarmBean.getUuid() + " 数据分类=" + alarmBean.getType() + " 报警子类型= " + alarmBean.getAlarmType());
        //保存alarmMessage表
        String orgCode = "001-001";
        Long tenentId = 1L;
        if (StringUtils.isNotBlank(alarmBean.getOrgCode())) {
            orgCode = "001-" + alarmBean.getOrgCode();
        }
//        if (alarmBean.getTenentId() != null) {
//            tenentId = alarmBean.getTenentId();
//        }
        alarmBean.setOrgCode(orgCode);
        alarmBean.setTenentId(tenentId);
        if (StringUtils.isNotBlank(alarmBean.getUuid())) {
            alarmBean.setUId(Long.parseLong(alarmBean.getUuid()));
        }
        if (StringUtils.isNotBlank(alarmBean.getAlarmType())) {
            alarmBean.setSubTypeName(ApiAlarmSubTypeEnum.getNameByCode(alarmBean.getAlarmType()));
            if (alarmBean.getAlarmType().equals(ApiAlarmSubTypeEnum.LEAVE_ALARM.getCode()) || alarmBean.getAlarmType().equals(ApiAlarmSubTypeEnum.INTRUDE_ALARM.getCode())){
                if (StringUtils.isNotBlank(alarmBean.getJobNumber()) && checkIsUuid(alarmBean.getJobNumber())){
                    try {
                        BaseUser user = baseUserDao.findByCode(alarmBean.getCodeInfo());
                        ProcessMapListBean bean = newProcessService.getProcDetail(alarmBean.getJobNumber(),user);
                        log.info("=========流程引擎获取数据==========="+JSON.toJSONString(bean));
                        alarmBean.setAlarmInfo(bean.getName()+bean.getSerialNumber()+"，【"+alarmBean.getRealName()+"】产生"+ApiAlarmSubTypeEnum.getNameByCode(alarmBean.getAlarmType()));
                        alarmBean.setSerialNumber(bean.getSerialNumber());
                        alarmBean.setProcessInstanceId(bean.getProcessInstanceId());
                    } catch (Exception ignored) {
                    }
                }

            }
        }

        if (this.getAlarmSwitch(alarmBean.getTenentId(), alarmBean.getOrgCode())) {
            alarmMessageService.saveAlarm(reqBean.getType(), alarmBean);
            //推送报警
            v3WebSocketAlarm(reqBean.getType(), tenentId, orgCode);
        }
    }

    /**
     * 检查字符串是否是合法的uuid,
     *
     * @param uuidStr
     * @return 是返回true,不是返回false
     */
    public static boolean checkIsUuid(String uuidStr) {
        try {
            UUID.fromString(uuidStr).toString();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public String ipTest(Integer type) {
        if (type.intValue() == 0) {
            return IpUtil.getHostIP();
        } else {
            return INetUtil.getHostIp();
        }
    }

    @Override
    public Integer getScUserData(String orgCode, Long tenentId) {
        ResponseEntity<LocateLoginRespDto> responseEntity = locateServerService.orientationSave(new OrientationSearchBean(locateServerService.getBuildIdByTenentIdAndOrgCode(tenentId, orgCode)), LocateLoginRespDto.class, "v2areaPersonCount", tenentId, orgCode);
        if (responseEntity == null) {
            log.error("获取大屏人员v2areaPersonCount错误...ResponseEntity is null");
        } else {
            LocateLoginRespDto dto = responseEntity.getBody();
            if (null != dto && responseEntity.getStatusCode() != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                if (StringUtils.isNotBlank(dto.getErrMsg())||dto.getCode().intValue()!=0){
                    log.error("获取大屏人员v2areaPersonCount...异常{}",JSONUtil.toJsonStr(dto));
                }
                if (dto.getData() != null) {
                    String string = JSONUtil.toJsonPrettyStr(dto.getData());
                    List<OrientationScPersionCountBean> datas = JSONUtil.toList(string, OrientationScPersionCountBean.class);
                    BaseConfig config = baseConfigService.findByTenentIdAndOrgCodeAndCode2(tenentId, orgCode, BaseConfigCodes.LOCATE_AREA_NAME);
                    if (config == null || StringUtils.isBlank(config.getValue())) {
                        log.error("获取大屏人员v2areaPersonCount...配置项为空");
                        return 0;
                    }
                    Integer num = 0;
                    return this.getScUserDataNum(datas, config.getValue(), num);

                } else {
                    log.error("获取大屏人员v2areaPersonCount...data is null");
                }
            }
        }
        return 0;
    }

    private Integer getScUserDataNum(List<OrientationScPersionCountBean> datas, String areaName, Integer num) {
        if (CollectionUtil.isNotEmpty(datas)) {
            for (OrientationScPersionCountBean data : datas) {
                if (data.getAreaName().equals(areaName) && CollectionUtil.isNotEmpty(data.getEachEmployeeTypeCount())) {
                    return data.getEachEmployeeTypeCount().stream().filter(item -> item.getPersonCount() != null).map(OrientationScPersionCountItemBean::getPersonCount).reduce(Integer::sum).get();
                } else {
                    this.getScUserDataNum(data.getAreas(), areaName, num);
                }
            }
        }
        return num;
    }


    private void v3WebSocketAlarm(String type, Long tenentId, String orgCode) {
        if (type.equals(ApiAlarmTypeEnum.AREA_ALARM.getCode())) {
            //区域报警
            List<OrientationPageAlarmCertificateOrAreaBean> areaBeans = pageCertificateOrAreaAlarm(tenentId, orgCode, new OrientationSearchBean(0, 100, "pageAreaAlarm"));
            MonitorPointDataWebSocket.sendInfo(Lists.newArrayList(areaBeans), WebsocketDataType.LOCATE_AREA_ALRAM.getIndex());
        } else if (type.equals(ApiAlarmTypeEnum.JOBA_LARM_EVENT.getCode())) {
            //作业报警
            List<OrientationPageAlarmCertificateOrAreaBean> certBeans = pageCertificateOrAreaAlarm(tenentId, orgCode, new OrientationSearchBean(0, 100, "pageCertificateAlarm"));
            MonitorPointDataWebSocket.sendInfo(Lists.newArrayList(certBeans), WebsocketDataType.LOCATE_CERTIFICATE_ALARM.getIndex());
        } else if (type.equals(ApiAlarmTypeEnum.ALARM_EVENT.getCode())) {
            //车辆报警
            List<OrientationPageAlarmCertificateOrAreaBean> certBeans = pageCertificateOrAreaAlarm(tenentId, orgCode, new OrientationSearchBean(0, 100, "pagCarAlarm"));
            MonitorPointDataWebSocket.sendInfo(Lists.newArrayList(certBeans), WebsocketDataType.LOCATE_CAR_ALARM.getIndex());
        }
        OrientationAlarmCountBean socketBean = alarmMessageCount(tenentId, orgCode);
        MonitorPointDataWebSocket.sendInfo(Lists.newArrayList(socketBean), WebsocketDataType.LOCATE_ALRAM_COUNT.getIndex());
    }

    private List<OrientationCheckSnInAreaReturnBean> convert(List<LinkedHashMap> records) {
        return records == null ? Lists.newArrayList() : records.stream().map(OrientationCheckSnInAreaReturnBean::new).collect(Collectors.toList());
    }

    private OrientationCheckSnInAreaBoxBean getSnInAreaBean(Long userId, Long pointId, String message) {
        OrientationCheckSnInAreaBoxBean boxBean = new OrientationCheckSnInAreaBoxBean();
        //BPInspectPoint
        OrientationCheckSnInAreaBean bean = new OrientationCheckSnInAreaBean();
        bean.setBuildId(locateServerService.getBuildId());
        List<String> snList = new ArrayList<>();
        Optional<BaseUser> obu = baseUserDao.findById(userId);
        if (obu.isPresent()) {
            if (StringUtils.isNotBlank(obu.get().getSn())) {
                snList.add(obu.get().getSn());
            } else {
                log.error("sn号是否在区域--userid{} Sn号不存在" + userId);
                message = "该人员未配置定位卡片";
            }
        } else {
            log.error("sn号是否在区域--userid{} 人员不存在" + userId);
            message = "该人员不存在";
        }
        bean.setSnList(snList);
        List<OrientationCheckSnInAreaItemBean> rails = new ArrayList<>();
        Optional<BPInspectPoint> obp = inspectPointDao.findById(pointId);
        if (obp.isPresent()) {
            BPInspectPoint point = obp.get();
            if (point.getLocationType() != null && (point.getLocationType().equals("人员定位") || point.getLocationType().equals("地图")) && StringUtils.isNotBlank(point.getInspectLocation())) {
                OrientationCheckSnInAreaItemBean itemBean = new OrientationCheckSnInAreaItemBean();
                List<OrientationPointOtherBean> pointsList = new ArrayList<>();
                BaseConfig config = baseConfigService.findConfig(Context.getCurrentTenantId(), Context.getCompanyCode(), "wwyt.server.maptype");
                if (config == null || StringUtils.isBlank(config.getValue())) {
                    log.error("配置项 wwyt.server.maptype is null");
                    message = "请完善地图配置项";
                } else if (config.getValue() != null && config.getValue().equals("2.5D")) {
                    MapUtils.ThreeDPoints points = MapUtils.parse3DPointsFromJson(point.getInspectLocation());
                    if (points != null) {
                        //楼层
                        if (points.getFloorId() < 0) {
                            itemBean.setFloorNo("FB" + points.getFloorId());
                        } else {
                            itemBean.setFloorNo("Floor" + points.getFloorId());
                        }
                        List<Point> pointList = points.getPoints();
                        for (Point p : pointList) {
                            OrientationPointOtherBean coordinateBean = new OrientationPointOtherBean();
                            coordinateBean.setX(p.getX());
                            coordinateBean.setY(p.getY());
                            pointsList.add(coordinateBean);
                        }
                    }
                } else if (config.getValue() != null && config.getValue().equals("3D")) {
                    MapUtils.SafetyPoints points = MapUtils.parse3DSafetyPointsFromJson(point.getInspectLocation());
                    if (points != null) {
                        //楼层
                        if (points.getFloorId() < 0) {
                            itemBean.setFloorNo("FB" + points.getFloorId());
                        } else {
                            itemBean.setFloorNo("Floor" + points.getFloorId());
                        }
                        List<MapUtils.SafetyPoint> pointList = points.getPoints();
                        for (MapUtils.SafetyPoint p : pointList) {
                            OrientationPointOtherBean coordinateBean = new OrientationPointOtherBean();
                            coordinateBean.setX(p.getX());
                            coordinateBean.setY(p.getY());
                            pointsList.add(coordinateBean);
                        }
                    }
                }
                itemBean.setPointsList(pointsList);
                rails.add(itemBean);
            } else {
                log.error("sn号是否在区域--BPInspectPointId{} 检查点定位方式错误" + pointId);
                message = "检查点定位有误";
            }
        } else {
            log.error("sn号是否在区域--BPInspectPointId{} 检查点Id不存在" + pointId);
            message = "检查点不存在";
        }
        bean.setRails(rails);
        boxBean.setMessage(message);
        boxBean.setBean(bean);
        return boxBean;
    }

    //获取 delete 承包商 bean
    private OrientationContractorBean getContractorDeleteBean(List<BpContractor> all) {
        OrientationContractorBean bean = new OrientationContractorBean();
        List<Long> uniqueIds = new ArrayList<>();
        bean.setBuildId(locateServerService.getBuildId());
        for (BpContractor contractor : all) {
            if (contractor.getUniqueId() == null) {
                log.info("承包商同步---删除 承包商id{} 的uniqueId 为空 ");
                return null;
            }
            uniqueIds.add(Long.valueOf(contractor.getUniqueId()));
        }
        bean.setData(uniqueIds);
        return bean;
    }

    //获取 add/alter 承包商 bean
    private OrientationContractorBean getContractorSaveBean(BpContractor contractor) {
        if (contractor.getUniqueId() == null) {
            log.info("承包商同步---修改 承包商id{} 的uniqueId 为空 ");
            return null;
        }
        OrientationContractorBean bean = new OrientationContractorBean();
        bean.setBuildId(locateServerService.getBuildId());
        bean.setContractorName(contractor.getCompanyName());
        bean.setUniqueId(contractor.getUniqueId().toString());
        bean.setPrincipalName(contractor.getSafetyDirector());
        bean.setPhone(contractor.getSafetyDirectorTel());
        return bean;
    }

    private OrientationRiskDistrictSaveBean saveDistrict(RiskDistrict district, String flag) {
        OrientationRiskDistrictSaveBean bean = new OrientationRiskDistrictSaveBean();
        bean.setBuildId(locateServerService.getBuildId());
        bean.setAreaName(district.getName());
        //修改获取雪花ID
        if (flag.equals("alterArea")) {
            if (StringUtils.isNotBlank(district.getUniqueId())) {
                bean.setUniqueId(district.getUniqueId());
            } else {
                //uniqueId为空->走新增功能
                flag = "addArea";
            }
        }
        //坐标
        List<OrientationPointBean> cList = new ArrayList<>();
        BaseConfig config = baseConfigService.findConfig(Context.getCurrentTenantId(), Context.getCompanyCode(), "wwyt.server.maptype");
        if (config == null || StringUtils.isBlank(config.getValue())) {
            log.error("配置项 wwyt.server.maptype is null");
            return null;
        } else if (config.getValue() != null && config.getValue().equals("2.5D")) {
            MapUtils.ThreeDPoints points = MapUtils.parse3DPointsFromJson(district.getCoordinates());
            if (points == null) {
                return null;
            }
            //楼层
            if (points.getFloorId() < 0) {
                bean.setFloorNo("FB" + points.getFloorId());
            } else {
                bean.setFloorNo("Floor" + points.getFloorId());
            }
            // 默认室内
            bean.setInOrOutSide("in");
            List<Point> pointList = points.getPoints();
            for (Point p : pointList) {
                OrientationPointBean coordinateBean = new OrientationPointBean();
                coordinateBean.setLng(p.getX());
                coordinateBean.setLat(p.getY());
                cList.add(coordinateBean);
            }

        } else if (config.getValue() != null && config.getValue().equals("3D")) {
            MapUtils.SafetyPoints points = MapUtils.parse3DSafetyPointsFromJson(district.getCoordinates());
            if (points == null) {
                return null;
            }
            //楼层
            if (points.getFloorId() < 0) {
                bean.setFloorNo("FB" + points.getFloorId());
            } else {
                bean.setFloorNo("Floor" + points.getFloorId());
            }
            // 室内/室外 批量画围栏后围栏室内外根据inOrOutSide字段决定
//            if (points.getBuildingId() != null && points.getBuildingId().equals("000000")) {
//                bean.setInOrOutSide("out");
//            } else {
//                bean.setInOrOutSide("in");
//            }
            if (StringUtils.isNotBlank(points.getInOrOutSide())) {
                bean.setInOrOutSide(points.getInOrOutSide());
            } else {
                bean.setInOrOutSide("out");
            }
            List<MapUtils.SafetyPoint> pointList = points.getPoints();
            for (MapUtils.SafetyPoint p : pointList) {
                OrientationPointBean coordinateBean = new OrientationPointBean();
                coordinateBean.setLng(p.getX());
                coordinateBean.setLat(p.getY());
                cList.add(coordinateBean);
            }

        }
        bean.setPointsList(cList);
        if (flag.equals("addArea")) {
            log.error(district.getName() + " 区域同步....新增 " + JSON.toJSONString(bean));
            addArea(bean, LocateLoginRespDto.class, flag, district);
        } else if (flag.equals("alterArea")) {
            log.error(district.getName() + " 区域同步....修改 " + JSON.toJSONString(bean));
            alterArea(bean, LocateLoginRespDto.class, flag);
        }
        return bean;
    }


    //获取 delete Bean
    private OrientationRiskDistrictDeleteBean getDistrictDeleteBean(List<RiskDistrict> all) {
        OrientationRiskDistrictDeleteBean bean = new OrientationRiskDistrictDeleteBean();
        bean.setBuildId(locateServerService.getBuildId());
        List<String> uniqueIds = new ArrayList<>();
        for (RiskDistrict district : all) {
            if (StringUtils.isNotBlank(district.getUniqueId())) {
                uniqueIds.add(district.getUniqueId());
            } else {
                log.info("风险区域同步删除,id为{}的uniqueId为空" + district.getId());
            }
        }
        bean.setUniqueIds(uniqueIds);
        return bean;
    }

    private void saveUniqueId(RiskDistrict district, String uniqueId) {
        district.setUniqueId(uniqueId);
        riskDistrictDao.save(district);
    }


}
